<?php

namespace app\member\controller;


use app\common\constant\TemplateConstant;
use app\common\controller\Alisms;
use app\common\model\ViperUser;
use think\Db;
use think\Exception;
use app\common\controller\Smscm;
use app\common\model\ViperCard as ViperCardModel;
use think\Validate;

/**
 * 会员卡控制器
 */
class ViperCard extends Base
{
    public $noNeedLogin = [];

    /**
     *   获取会员卡类型充值模板，普通卡
     **/
    public function getList()
    {
        if ($this->request->isPost()) {
            $user_info = $this->user_info;
            $post = $this->request->post();
            $limit = !empty($post['limit']) ? $post['limit'] : 10;
            if (empty($post['viper_type_id'])) {
                $this->result('会员卡类型必填', '', 204);
            }
            $query = Db::name('qt_viper_recharge_template')->alias('rt')
                ->field([
                    'rt.id',
                    'rt.name',
                    'rt.amount',
                    'rt.give_amount',
                    'vt.name type_name',
                ])
                ->leftJoin('qt_viper_type vt', 'rt.viper_type_id = vt.id')
                ->where([
                    'vt.store_id' => $user_info['store_id'],
                    'rt.viper_type_id' => $post['viper_type_id'],
                ]);
            $data = $query->order('rt.id desc')->paginate($limit);
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }


    /**
     * 获取会员卡类型列表
     */
    public function getViperCardType()
    {

        $user_info = $this->user_info;
        $data = Db::name('qt_viper_type')->field([
            'id',
            'store_id',
            'name',
            'name',
        ])->where(['store_id' => $user_info['store_id']])->select();

        $this->result('查询成功', $data, 200);
    }


    /**
     * 获取我的会员卡列表
     */
    public function getMyViperCard()
    {
        if ($this->request->isPost()) {

            $viper_card_id = $this->request->post('vip_card_id', '');
            $recharge_template_id = $this->request->post('template_id', '');

            $user_info = $this->user_info;

            $query = Db::name('qt_viper_card')
                ->field('vc.id,vc.viper_type_id,vc.avatar,vc.mobile,vc.give_total_amount,vc.update_time,
                vc.birthday,vc.card_no,vc.amount,vt.name as type_name,vc.name,vc.create_time,
                vc.gender,vc.score,vc.amount,vc.status,vc.give_amount,s.name as store_name')
                ->alias('vc')
                ->leftJoin('qt_viper_type vt', 'vc.viper_type_id = vt.id')
                ->leftJoin('qt_store s', 'vc.store_id = s.id')
                ->where('vc.store_id', '=', $user_info['store_id'])
                ->where('vc.viper_user_id', '=', $user_info['id']);

            if (!empty($viper_card_id)) {
                $query->where('vc.id', '=', $viper_card_id);
            }

            if (!empty($recharge_template_id)) {
                $query->where('vc.recharge_template_id', '=', $recharge_template_id);
            }

            $data = $query->select();
            $this->result('查询成功', $data, 200);
        }

        $this->result('无效的请求', '', 204);
    }


    /**
     * 创建会员卡
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createViperCard()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $rule = [
                'code' => 'require',
                'mobile' => 'require',
            ];
            $message = [
                'code.require' => '验证码必填',
                'mobile.mobile' => '手机号必填',
            ];
            $validate = new Validate($rule, $message);
            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }

            //校验验证码
            $sms = new Alisms();
            $check_sms = $sms->check_smscode($data['mobile'], $data['code'], 1);
            if ($check_sms['code'] != 200) {
                $this->result($check_sms['msg'], '', 204);
            }

            $template_res = Db::name('qt_viper_recharge_template')->where('id', $data['recharge_template_id'])->find();
            if (empty($template_res)) {
                $this->result('没有找到对应的模板', '', 204);
            }
            $user = ViperUser::where(['phone' => $data['mobile']])->find();
            $temp_arr = [
                'mobile' => $data['mobile'],
                'template_type' => TemplateConstant::TEMPLATE_TYPE_DEFAULT,
                //'card_no' => $data['card_no'],
                'viper_user_id' => !empty($user['id']) ? $user['id'] : 0,
                'user_id' => $this->user_info['id'],
                'name' => $data['name'],
                'gender' => $data['gender'],
                'saler_id' =>  0,//门店端没有销售
                'type' =>  0,//销售类型:1=楼面,2=技师
                'viper_type_id' => $data['viper_type_id'],
                'birthday' => strtotime($data['birthday']),
                'pay_content' => '',
                'neima' => '',
                'store_id' => $this->user_info['store_id'],
                'amount' => $template_res['amount'],//充值金额
                'total_amount' => $template_res['amount'],
                'give_amount' => $template_res['give_amount'],//赠送金额
                'give_total_amount' => $template_res['give_amount'],
                'template_id' => $data['recharge_template_id'],
                'passwd' => $data['passwd'],//密码
                'recharge_temp_name' => $template_res['name'],
            ];

            ViperCardModel::openCard($temp_arr, $this->user_info); //开卡
            $this->result('操作成功', '', 200);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }


    /**
     * 会员卡充值
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recharge()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $user_info = $this->user_info;
            if (empty($getData['viper_card_id']) || !isset($getData['template_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $cardRes = Db::name('qt_viper_card')->where('id', $getData['viper_card_id'])->find();
            if (empty($cardRes)) {
                $this->result('会员卡不存在', '', 204);
            }
            $templateRes = Db::name('qt_viper_recharge_template')->where('id', $cardRes['recharge_template_id'])->find();
            $userViper = Db::name('qt_user_viper')->where('id', $cardRes['user_id'])->find();

            $insert = [
                'store_id' => $user_info['store_id'],
                'user_id' => $cardRes['user_id'],
                'viper_card_id' => $getData['viper_card_id'],
                'amount' => $templateRes['amount'],
                'give_amount' => $templateRes['give_amount'],
                'recharge_tempid' => $templateRes['id'],
                'pay_status' => 1,
                'order_no' => create_card_recharge(),
                'type' => '2',
                'card_amount' => $templateRes['amount'] + $templateRes['give_amount'],
                'commission' => number_format(($templateRes['amount'] * $templateRes['rate']) / 100, 2),
                'creater' => $user_info['id'],
                'create_time' => time(),
                'card_type' => '1',
                'status' => '1',
                'recharge_content' => '',
                'recharge_temp_name' => $templateRes['name'],
            ];
            $viperCard = [
                'amount' => $cardRes['amount'] + $templateRes['amount'],
                'give_amount' => $cardRes['give_amount'] + $templateRes['give_amount'],
                'give_total_amount' => $cardRes['give_total_amount'] + $templateRes['give_amount'],
                'total_amount' => $cardRes['total_amount'] + $templateRes['amount'],
            ];
            $user = [
                'money' => $userViper['money'] + $templateRes['amount'],
                'integral' => $userViper['integral'] + $templateRes['integral'],
            ];

            try {
                Db::startTrans();
                //插入日志
                Db::name('qt_viper_card_recharge_log')->insert($insert);
                //更新会员卡
                Db::name('qt_viper_card')->where('id', $getData['viper_card_id'])->update($viperCard);
                //更新用户
                Db::name('qt_user_viper')->where('id', $cardRes['user_id'])->update($user);
                Db::commit();

                $this->result('充值成功', '', 200);
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('充值失败', '', 204);
            }
        } else {
            $this->result('请求错误', '', 204);
        }

    }

}
